const express = require('express');
const { query } = require('../config/database');
const { authenticateToken } = require('../middleware/auth');

const router = express.Router();

// 获取策略列表
router.get('/', authenticateToken, async (req, res) => {
  try {
    const { page = 1, limit = 20, search = '', type = '' } = req.query;
    const offset = (page - 1) * limit;

    let whereConditions = ['1=1'];
    let params = [];

    if (search) {
      whereConditions.push('(name LIKE ? OR description LIKE ?)');
      params.push(`%${search}%`, `%${search}%`);
    }

    if (type) {
      whereConditions.push('type = ?');
      params.push(type);
    }

    const whereClause = whereConditions.join(' AND ');

    const countResult = await query(
      `SELECT COUNT(*) as total FROM strategies WHERE ${whereClause}`,
      params
    ) || [{ total: 0 }];

    const [{ total = 0 } = {}] = countResult;

    const strategies = await query(
      `SELECT s.*, u.name as creator_name 
       FROM strategies s 
       LEFT JOIN users u ON s.created_by = u.id 
       WHERE ${whereClause} 
       ORDER BY s.created_at DESC 
       LIMIT ? OFFSET ?`,
      [...params, parseInt(limit), offset]
    );

    res.json({
      data: strategies,
      pagination: {
        page: parseInt(page),
        limit: parseInt(limit),
        total: total,
        pages: Math.ceil(total / limit)
      }
    });

  } catch (error) {
    console.error('获取策略列表错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 创建策略
router.post('/', authenticateToken, async (req, res) => {
  try {
    const { 
      name, 
      description, 
      type, 
      config, 
      fundIds, 
      weights 
    } = req.body;
    const userId = req.user.id;

    const result = await query(
      'INSERT INTO strategies (name, description, type, config, status, created_by, created_at) VALUES (?, ?, ?, ?, ?, ?, NOW())',
      [name, description, type, JSON.stringify(config), 'active', userId]
    ) || { insertId: 0 };

    const strategyId = result.insertId;

    // 保存策略基金配置
    if (fundIds && fundIds.length > 0) {
      for (let i = 0; i < fundIds.length; i++) {
        await query(
          'INSERT INTO strategy_funds (strategy_id, fund_id, weight) VALUES (?, ?, ?)',
          [strategyId, fundIds[i], weights[i] || 0]
        );
      }
    }

    res.status(201).json({
      message: '策略创建成功',
      strategyId
    });

  } catch (error) {
    console.error('创建策略错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 获取策略详情
router.get('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const rows = await query('SELECT * FROM strategies WHERE id = ?', [id]) || [];
    const [strategy] = rows;
    if (!strategy) return res.status(404).json({ message: '策略不存在' });

    // 获取策略基金配置
    const funds = await query(
      `SELECT sf.*, f.name as fund_name, f.code as fund_code 
       FROM strategy_funds sf 
       LEFT JOIN funds f ON sf.fund_id = f.id 
       WHERE sf.strategy_id = ?`,
      [id]
    ) || [];

    // 获取策略回测结果
    const backtestResults = await query(
      'SELECT * FROM strategy_backtest WHERE strategy_id = ? ORDER BY test_date DESC LIMIT 1',
      [id]
    );

    res.json({
      strategy,
      funds,
      backtestResults: backtestResults && backtestResults[0] || null
    });
  } catch (error) {
    console.error('获取策略详情错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 策略回测
router.post('/:id/backtest', authenticateToken, async (req, res) => {
  try {
    const { id } = req.params;
    const { startDate, endDate, initialCapital } = req.body;

    // 这里应该实现实际的回测逻辑
    // 目前返回模拟数据
    const mockResult = {
      strategy_id: id,
      start_date: startDate,
      end_date: endDate,
      initial_capital: initialCapital,
      final_capital: initialCapital * 1.15,
      total_return: 0.15,
      annual_return: 0.12,
      max_drawdown: -0.08,
      sharpe_ratio: 1.2,
      test_date: new Date()
    };

    await query(
      'INSERT INTO strategy_backtest SET ?',
      mockResult
    );

    res.json({
      message: '回测完成',
      result: mockResult
    });

  } catch (error) {
    console.error('策略回测错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 策略再平衡
router.post('/:id/rebalance', authenticateToken, async (req, res) => {
  try {
    const { id } = req.params;
    const { newWeights } = req.body;

    // 更新策略基金权重
    for (const item of newWeights) {
      await query(
        'UPDATE strategy_funds SET weight = ? WHERE strategy_id = ? AND fund_id = ?',
        [item.weight, id, item.fundId]
      );
    }

    res.json({ message: '策略再平衡成功' });

  } catch (error) {
    console.error('策略再平衡错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

module.exports = router; 